package com.echatim.test.tools;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;

/**
 * @author Daizhiqiang <zqdai@sailfish.com.cn>
 * create by 2021/6/9 9:25
 * Description: easyim
 **/
public class LoopRunner {
    public static void run(String runnerName, Integer cnt, Consumer<Void> target){
        int i = cnt;
        long start = System.currentTimeMillis();
        while (i-- > 0){
            target.accept(null);
        }
        long end = System.currentTimeMillis();
        System.out.println(String.format("LoopRunner run 【%s】 finish, use %dms",runnerName, (end-start)));
    }
    // 多线程运行
    public static void multiRun(String runnerName, Integer cnt, Consumer<Void> target){
        long start = System.currentTimeMillis();
        List<Future> futures = new ArrayList<>();
        int multiThreadCnt = 10;
        ExecutorService pool = Executors.newFixedThreadPool(multiThreadCnt);
        for(int i = 0; i < multiThreadCnt; i++){
            Future future = pool.submit(()->{
                LoopRunner.run(runnerName, cnt/multiThreadCnt, target);
            });
            futures.add(future);
        }
        // 等待所有子线程完成
        futures.forEach(v->{
            try {
                v.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        });

        long end = System.currentTimeMillis();
        System.out.println(String.format("LoopRunner multiRun 【%s】 finish, use %dms",runnerName, (end-start)));
    }
}
